package com.study.mq.config;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ysy
 * @version 1.0
 * @Title: RabbiConfig
 * @Note <b>ProjectName:</b> Pre-research
 * <br><b>PackageName:</b> com.study.mq.rabbitMq.config
 * <br><b>ClassName:</b>
 * <br><b>Date:</b>
 */
@Configuration
@EnableRabbit
public class RabbiConfig {

    // 连接配置，springboot自动装配
    @Bean
    public ConnectionFactory connectionFactory(){
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setUri("amqp://test:test@127.0.0.1:5672");
        return factory;
    }

    // RabbitAdmin：用于声明Exchange，Queue，Binging
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        // 启动时构建连接，默认为true
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }

    //RabbitTemplate：发送和接收消息
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        return rabbitTemplate;
    }



    @Bean
    public SimpleMessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory){
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames("test1");
        // 设置自动ack确认
        container.setAcknowledgeMode(AcknowledgeMode.AUTO);
        MessageListenerAdapter adapter = new MessageListenerAdapter(new MessageHandler());
        //指定Json转换器：RabbitMQ自带的Jackson2JsonMessageConverter转换器【不指定contentType】
        adapter.setMessageConverter(new Jackson2JsonMessageConverter());
        //设置处理器的消费消息的默认方法
        adapter.setDefaultListenerMethod("onMessage");
        container.setMessageListener(adapter);

        return container;
    }
}
